package com.corner.model.leancloud.helper;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.AVIMMessage;
import com.avos.avoscloud.im.v2.AVIMTypedMessage;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCallback;
import com.avos.avoscloud.im.v2.callback.AVIMMessagesQueryCallback;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;
import com.corner.app.App;
import com.corner.model.cornerservice.domain.Conversation;
import com.corner.model.cornerservice.domain.User;
import com.corner.model.cornerservice.helper.UserHelper;
import com.corner.model.cornerservice.service.Service;
import com.corner.model.cornerservice.service.exception.BaseException;
import com.corner.model.cornerservice.utils.ServiceQuery;

import com.corner.model.db.ConversationDao;
import com.corner.model.db.DBConstans;
import com.corner.model.db.Session;
import com.corner.utils.LogUtil;
import com.corner.utils.SharePreferenceUtil;
import com.google.gson.annotations.Expose;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2015/7/26，22.09.
 * 描述：
 */
public class HistoryMessageHelper extends BaseMessageHelper{

    public static final String HAS_GET_HISTORY_MESSAGES = "hasGetHistoryMessages";
    public static final int QUERY_LIMIT = 10;

    /**
     * 获取该条消息之前的消息
     *
     * @param avimConversation
     * @param msgId
     * @param timeStamp
     * @return
     */
    public static void getPreMessage(final AVIMConversation avimConversation, final String msgId, final long timeStamp, final GetPreMessageCallabck getPreMessageCallabck) {
        avimConversation.fetchInfoInBackground(new AVIMConversationCallback() {
            @Override
            public void done(AVIMException e) {
                if (e != null)
                    return;
                AVIMMessagesQueryCallback callback = new AVIMMessagesQueryCallback() {
                    @Override
                    public void done(List<AVIMMessage> messages, AVIMException e) {
                        if (null != e || messages == null || messages != null && messages.size() == 0) {
                            // 出错了:(
                            getPreMessageCallabck.onGetPreMessage(false);
                        } else {
                            saveMessages(messages, avimConversation).subscribe(new Action1<Object>() {
                                @Override
                                public void call(Object o) {
                                    getPreMessageCallabck.onGetPreMessage(true);
                                }
                            });
                        }
                    }
                };
                try {
                    if (msgId != null) {
                        avimConversation.queryMessages(msgId, timeStamp, QUERY_LIMIT, callback);
                    } else {
                        avimConversation.queryMessages(QUERY_LIMIT, callback);
                    }
                } catch (IndexOutOfBoundsException e1) {
                    getPreMessageCallabck.onGetPreMessage(false);
                }

            }
        });
    }

    /**
     * 向数据库中保存查询得到的messages
     * @param messages
     * @param avimConversation
     * @return
     */
    private static Observable<Object> saveMessages(final List<AVIMMessage> messages, final AVIMConversation avimConversation) {
        return Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                // 成功，可以将消息加入缓存，同时更新 UI
                List<Session> sessions = new ArrayList<Session>();
                for (AVIMMessage item : messages) {
                    AVIMTypedMessage message = (AVIMTypedMessage) item;
                    Session session = generateSession(message, avimConversation);
                    if (session != null) {
                        sessions.add(session);
                    }
                }
                App.application.daoSession.getSessionDao().insertInTx(sessions);
                subscriber.onNext(null);
            }
        });
    }

    /**
     * 获取历史消息
     */
    public static void getHistoryMessage() {
        String userConfig = SharePreferenceUtil.getString(App.application, User.getCurrentUser().getObjectId().toString());
        if (!TextUtils.isEmpty(userConfig)) {
            JSONObject jsonObject = JSONObject.parseObject(userConfig);
            Boolean hasGet = jsonObject.getBoolean(HAS_GET_HISTORY_MESSAGES);
            if (hasGet == null || !hasGet) {
                getConversations();
            }
        } else {
            getConversations();
        }
    }

    /**
     * 获取conversation会话
     */
    private static void getConversations() {
        //设置以获取历史信息
        setHasGetHistoryMessage(true);
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                try {
                    getConversationCreateBy(true);
                    getConversationCreateBy(false);
                } catch (BaseException e) {
                    e.printStackTrace();
                    setHasGetHistoryMessage(false);
                }
            }
        }).subscribeOn(Schedulers.io()).subscribe();
    }

    /**
     * 获取conversation
     *
     * @param isMe true：我创建的 false：对方创建的
     * @throws BaseException
     */
    private static void getConversationCreateBy(boolean isMe) throws BaseException {
        int count = 0;
        while (true) {
            final ServiceQuery query = new ServiceQuery();
            query.setLimit(10);
            query.setLastId(count);
            count += 10;
            if (isMe) {
                query.equal(Conversation.MAIN_USER, User.getCurrentUser().getObjectId(), ServiceQuery.FOREIGN_KEY);
            } else {
                query.equal(Conversation.CUSTOM_USER, User.getCurrentUser().getObjectId(), ServiceQuery.FOREIGN_KEY);
            }
            List<Conversation> conversations = Service.getInstance().conversationService.list(query.toString());
            if (conversations != null && conversations.size() > 0) {
                for (Conversation conversation : conversations) {
                    saveConversation(conversation);
                    saveMessages(conversation);
                    LogUtil.e("conversation finish");
                }
            }
            if (conversations == null || conversations != null && conversations.size() < 10) {
                break;
            }
        }
    }

    /**
     * 设置已经获取历史消息
     */
    private static void setHasGetHistoryMessage(boolean hsGet) {
        String userConfig = SharePreferenceUtil.getString(App.application, User.getCurrentUser().getObjectId().toString());
        JSONObject jsonObject;
        if (!TextUtils.isEmpty(userConfig)) {
            jsonObject = JSONObject.parseObject(userConfig);
        } else {
            jsonObject = new JSONObject();
        }
        jsonObject.put(HAS_GET_HISTORY_MESSAGES, hsGet);
        SharePreferenceUtil.saveString(App.application, User.getCurrentUser().getObjectId().toString(), jsonObject.toJSONString());
    }

    /**
     * 获取指定conversation的历史消息
     *
     * @param conversation
     */
    private static void saveMessages(final Conversation conversation) {
        final AVIMConversation avimConversation = MessageHelperV2.getInstance().getConversation(conversation.getConversationId());
        avimConversation.fetchInfoInBackground(new AVIMConversationCallback() {
            @Override
            public void done(AVIMException e) {
                if (e != null) {
                    setHasGetHistoryMessage(false);
                    return;
                }
                avimConversation.queryMessages(QUERY_LIMIT, new AVIMMessagesQueryCallback() {
                    @Override
                    public void done(List<AVIMMessage> messages, AVIMException e) {
                        if (null != e || messages == null || messages != null && messages.size() == 0) {
                            // 出错了:(
                        } else if (messages != null && messages.size() > 0) {
                            // 成功，可以将消息加入缓存，同时更新 UI
                            List<Session> sessions = new ArrayList<Session>();
                            LogUtil.e(String.valueOf(messages.size()));
                            for (AVIMMessage item : messages) {
                                AVIMTypedMessage message = (AVIMTypedMessage) item;
                                Session session = generateSession(message, avimConversation);
                                if (session != null) {
                                    sessions.add(session);
                                }
                            }
                            App.application.daoSession.getSessionDao().insertOrReplaceInTx(sessions);
                        }
                    }
                });
            }
        });
    }

    /**
     * 将message解析为session
     *
     * @param message
     * @param conversation
     * @return
     */
    private static Session generateSession(AVIMTypedMessage message, AVIMConversation conversation) {
        try {
            Session session = null;
            // 请按自己需求改写
            switch (message.getMessageType()) {
                case -1:
                    AVIMTextMessage textMsg = (AVIMTextMessage) message;
                    Map<String, Object> pamas = textMsg.getAttrs();
                    session = new Session();
                    session.setSessionId(pamas.get(DBConstans.SESSION_ID).toString());
                    session.setMessageId(textMsg.getMessageId());
                    session.setIsSent(DBConstans.SENT);
                    session.setType(pamas.get(DBConstans.TYPE).toString());
                    session.setTimestamp(new Date(textMsg.getTimestamp()));
                    setFromAndTo(conversation, session, textMsg);

                    session.setIsReaded(true);
                    session.setText(textMsg.getText());
                    switch (session.getType()){
                        case DBConstans.COMMENT:
                            session.setInfoId(Long.valueOf(pamas.get(DBConstans.INFOID).toString()));
                            break;
                        case DBConstans.SHARE:
                            session.setLocationId(Long.valueOf(pamas.get(DBConstans.LOCATION_ID).toString()));
                            break;
                        case DBConstans.PIC_AUDIO:
                            session.setPic(pamas.get(DBConstans.PIC).toString());
                            session.setAudio(pamas.get(DBConstans.AUDIO).toString());
                            session.setAudioDuration(pamas.get(DBConstans.AUDIODURATION).toString());
                            break;
                        case DBConstans.PIC:
                            session.setPic(pamas.get(DBConstans.PIC).toString());
                            break;
                        case DBConstans.AUDIO:
                            session.setAudio(pamas.get(DBConstans.AUDIO).toString());
                            session.setAudioDuration(pamas.get(DBConstans.AUDIODURATION).toString());
                            break;
                        case DBConstans.BLACK_LIST:
                            session = null;
                            break;
                    }
                    break;
            }
            return session;
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 设置from和to的userId
     *
     * @param conversation
     * @param session
     * @param avimTypedMessage
     */
    private static void setFromAndTo(AVIMConversation conversation, Session session, AVIMTypedMessage avimTypedMessage) {
        session.setFromUserId(avimTypedMessage.getFrom());
        session.setToUserId(searchDestinationOfMessage(conversation, session.getFromUserId()));
        if (session.getFromUserId().equals(User.getCurrentUser().getObjectId().toString())) {
            session.setSessionName(session.getToUserId());
        } else {
            session.setSessionName(session.getFromUserId());
        }
    }

    /**
     * 插入会话
     *
     * @param conversation
     */
    private static void saveConversation(Conversation conversation) {
        com.corner.model.db.Conversation dbConversation = App.application.daoSession.getConversationDao()
                .queryBuilder().where(ConversationDao.Properties.ConversationId.eq(conversation.getConversationId()))
                .unique();
        if (dbConversation == null) {
            dbConversation = new com.corner.model.db.Conversation();
            dbConversation.setConversationId(conversation.getConversationId());
            dbConversation.setMainUser(conversation.getMainUser().getObjectId().toString());
            dbConversation.setCustomUser(conversation.getCustomUser().getObjectId().toString());
            dbConversation.setCustomIsInBlackList(conversation.getCustomIsInBlackList());
            dbConversation.setMainIsInBlackList(conversation.getMainIsInBlackList());
            App.application.daoSession.getConversationDao().insertOrReplace(dbConversation);

            UserHelper.saveUserToDb(conversation.getMainUser());
            UserHelper.saveUserToDb(conversation.getCustomUser());
        }
    }




    /**
     * 获得以前的消息的回调
     */
    public interface GetPreMessageCallabck {
        void onGetPreMessage(boolean isSucess);
    }
}
